package com.jiuzhe.commercial.main;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioGroup;

import com.jiuzhe.commercial.R;
import com.jiuzhe.commercial.base.BaseApplication;
import com.jiuzhe.commercial.http.HttpClient;
import com.jiuzhe.commercial.ui.fragment.CountFragment;
import com.jiuzhe.commercial.ui.fragment.HomeFragment;
import com.jiuzhe.commercial.ui.fragment.HouseFragment2;
import com.jiuzhe.commercial.ui.fragment.MyFragment;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {

    private RadioGroup mRg_content_fragment;
    private ArrayList<Fragment> mFragments;
    private BaseApplication mApplication;
    private HomeFragment homeFragment = new HomeFragment();
    private HouseFragment2 houseFragment = new HouseFragment2();
    private MyFragment myFragment = new MyFragment();
    private CountFragment countFragment = new CountFragment();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mApplication = (BaseApplication) getApplication();
        mApplication.addActvity(this);
        initFragments();
        initView();
    }

    private void initView() {
        mRg_content_fragment = (RadioGroup) findViewById(R.id.rg_content_fragment);
        mRg_content_fragment.setOnCheckedChangeListener(this);
        changeFragment(0);
    }

    private void initFragments() {
        mFragments = new ArrayList<Fragment>();
        if (mFragments != null) {
            mFragments.add(homeFragment);
            mFragments.add(houseFragment);
            mFragments.add(countFragment);
            mFragments.add(myFragment);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        int position = group.indexOfChild(group.findViewById(checkedId));
        changeFragment(position);
    }

    // 替换fragment
    private void changeFragment(int position) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.fl_container, mFragments.get(position));
        transaction.commit();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        HttpClient.cancelRequest(this);
    }
}
